/**
 * Created by lihongbo on 2017/10/19.
 * http请求配置 使用axios
 */

import axios from 'axios'
import router from '../router'
import store from '../store'

// export const publicUrl = "https://mhrservice.auxgroup.com/HR92DEV/eHR_Attachments/";//"http://10.88.30.12/HR92DEV/eHR_Attachments/";//
export const publicUrl = "https://mhrservice.auxgroup.com/eHR_Attachments/";//"http://10.88.30.12/HR92DEV/eHR_Attachments/";//
// export const logoAttachPath = "https://mhrservice.auxgroup.com/eHR_Attachments/";//"http://10.88.30.12/eHR_Attachments/";//

// export const publicUrl = "http://open.auxgroup.com/mhrtest/";//"http://10.88.30.12/HR92DEV/eHR_Attachments/";//
// export const logoAttachPath = "https://mhrservice.auxgroup.com/eHR_Attachments/";//"http://10.88.30.12/eHR_Attachments/";//
//axios 配置
axios.defaults.timeout = 50000;
// axios.defaults.baseURL = publicUrl;
function clearCookies(){
//   let date=new Date();
//   date.setTime(date.getTime()-10000);
//   let keys=document.cookie.match(/[^ =;]+(?=\=)/g);
//   if (keys) {
//     for (let i = keys.length; i--;) {
//       document.cookie=keys[i]+"=0; expire="+date.toGMTString()+"; path=/";
//     }
//   }
}


//http request 拦截器
axios.interceptors.request.use(
  config => {
    store.commit('changeLoading', true);
    //const token = getCookie('session');
    //config.data = JSON.stringify(config.data);
    if(!config.headers || !config.headers['Content-Type']) {
      config.headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      }
    }
    /*if (token) {
      config.params = {'token': token};
    }*/

    return config;
  },
  err => {

    console.error("---#####--------")
    return Promise.reject(err);
  }
);

//http response 拦截器
axios.interceptors.response.use(
  response => {
    store.commit('changeLoading', false);
    if(response && 5002 === response.status) {

        // let confirm = window.confirm("请先登录系统")
        // if(confirm) {
          clearCookies();
          window.location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href;
          return;
        // }
    }
    //测试http拦截器
    /*if(response.data.success === true) {
      router.push({
        path: '/home/login',
        //参数
        //query: {redirect: 'abc'}
      })
    }*/

    if (response.data.errCode === 2) {
      router.push({
        path: '/',
        //query: {redirect: '/'}
      })
    }
    return response;
  },
  err => {
    console.error("xx---------------------------")
    let rerror = JSON.parse(JSON.stringify(err));
    console.error(rerror)
    if(rerror.response && 5002 === rerror.response.status) {

      // let confirm = window.confirm("请先登录系统。")
      // if(confirm) {
        clearCookies();
        window.location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href;
        return;
      // }
    }
    return Promise.reject(err.response.data);
  }
);

//axios 请求方法封装
/**
 * get 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function fetch(url, params = {}) {

  return new Promise((resolve, reject) => {
    axios.get(url, {params: params})
      .then(response => {
        if (5002 === response.status) {
          // let confirm = window.confirm("请先登录系统.")
          // if(confirm) {
            clearCookies();
            window.location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href;
            return;
          // }
          // return;
        }
        //console.log('get success', response.data)
        //if (response.data.retCode === '000000') {
        resolve(response.data);
        //} else {
          //console.log('请求成功，但是数据异常', response.data)
          //reject(response.data)
        //}
      })
      .catch(err => {
        reject(err);
      })

  })

}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
import qs from 'qs'
export function post(url, data = {}) {

  return new Promise((resolve, reject) => {

    axios.post(url, data)
      .then(response => {
          if (5002 === response.status) {
            // let confirm = window.confirm("请先登录系统!")
            // if(confirm) {
              clearCookies();
              window.location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href;
              this.$vux.alert.show({
                title: "警告",
                content: "用户未登录，请重试"
              });
              return;
            // }
          }
          resolve(response.data);
        },
        err => {
          reject(err);
        })

  })
}

export function jsonpost(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, {
      headers: {'Content-Type': 'application/json; charset=UTF-8'}
    })
      .then(response => {
          if (5002 === response.status) {

            // let confirm = window.confirm("请先登录系统  !")
            // if(confirm) {
              clearCookies();
              window.location.href = "https://open.auxgroup.com/oauth/oauth2url?appurl=" + window.location.href;
              this.$vux.alert.show({
                title: "警告",
                content: "用户未登录，请重试"
              });
              return;
            // }
          }
          resolve(response.data);
        },
        err => {
          reject(err);
        })

  })
}

/**
 *
 * @param json
 * @returns {string}
 */
export function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&")
}
